package com.engine.kq.biz;

import cn.hutool.core.date.DateUtil;
import com.customization.shunsheng.util.LeaveNumberUtil;
import com.engine.kq.log.KQLog;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 格式化昨天的考勤数据
 */
public class KQBalanceOfLeaveJob extends BaseCronJob {
    private KQLog kqLog = new KQLog();

    public void execute() {
        try {
            kqLog.info("begin do KQBalanceOfLeaveJob invoke ...");
            KQBalanceOfLeaveBiz.createBalanceOfLeave();
            kqLog.info("end do KQBalanceOfLeaveJob invoke  ...");

            //start
            //增加对外籍假期类型的处理
            List<String> leaveIdList = new ArrayList<>();
            RecordSet rs = new RecordSet();
            String getLeaveIdsSql = "select id from kq_LeaveRules where balanceEnable = 1";
            rs.executeQuery(getLeaveIdsSql);
            while (rs.next()) {
                String id = Util.null2String(rs.getString("id"));
                if (StringUtils.isNotBlank(id)) {
                    leaveIdList.add(id);
                }
            }

            if ( !leaveIdList.isEmpty()) {
                for (String id : leaveIdList) {
                    LeaveNumberUtil leaveNumberUtil = new LeaveNumberUtil();
                    leaveNumberUtil.clearForgResLeaveNumber(id);
                }
            }

            //end
            /*假期二开--外籍年假转结功能start*/
            BaseBean bb = new BaseBean();
            //获取外籍年假
            List<String> outLeaveList = new ArrayList<>();
            String acqTransferSql = "select ruleid from kq_LeaveRulesDetail where isTransfer = ?";
            rs.executeQuery(acqTransferSql, 1);//1-是
            while (rs.next()) {
                String ruleid = Util.null2String(rs.getString("ruleid"));
                if (StringUtils.isNotBlank(ruleid)) {
                    outLeaveList.add(ruleid);
                }
            }
            //获取当前日期，作为失效日期
            RecordSet rsn = new RecordSet();
            String nowDay = DateUtil.format(new Date(), "yyyy-MM-dd");
            String nowYear = DateUtil.format(new Date(), "yyyy");
            BigDecimal decimalMin = new BigDecimal("0");
            String acqMaxDaySql = "select transferNumber from kq_leaverulesdetail where leaveRulesId = ?";
            BigDecimal decimalMax = new BigDecimal("0");
            String acqResidueSql = "select resourceid,( baseAmount + baseAmount2 + extraAmount + extraAmount2 - usedAmount - usedAmount2) as residueAmount from kq_balanceOfLeave where leaveRulesId = ?" +
                    " and expirationDate = ?";
            String acqBalanceSql = "select count(*) as number from kq_balanceOfLeave where leaveRulesId = ? and expirationDate > '"+nowDay+"'";
            String addBalanceSql = "insert into kq_balanceOfLeave (leaverulesid,resourceid,belongyear,baseamount,extraamount," +
                    "usedamount,baseamount2,extraamount2,usedamount2,status,expirationDate,tiaoxiuamount) values (?,?,?,?,?,?," +
                    "?,?,?,?,?,?)";
            String modBalanceSql = "update kq_balanceofleave set baseAmount = ((select baseAmount from kq_balanceofleave where resourceid = ? and leaverulesid = ? ) + ? ) where where resourceid = ? and leaverulesid = ?";

            for ( String outLeaves : outLeaveList) {
                rs.executeQuery(acqMaxDaySql, outLeaves);
                while ( rs.next()) {
                    String transferNumber = Util.null2String( rs.getString("transferNumber"));
                    if (StringUtils.isBlank(transferNumber)) {
                        transferNumber = "0";
                    }
                    decimalMax = new BigDecimal(transferNumber);
                }
                rs.executeQuery(acqResidueSql, outLeaves, nowDay);
                while ( rs.next()) {
                    String resourceid = Util.null2String( rs.getString("resourceid"));
                    String residueAmountStr = Util.null2String( rs.getString("residueAmount"));
                    if ( (decimalMin.compareTo(new BigDecimal(residueAmountStr)) == -1) ) {
                        BigDecimal newResidueAmount = decimalMax.compareTo(new BigDecimal(residueAmountStr)) == -1 ? decimalMax : new BigDecimal(residueAmountStr);
                        rsn.executeQuery(acqBalanceSql, outLeaves);
                        Integer number = -1;
                        while ( rsn.next()) {
                            number = Util.getIntValue(Util.null2String( rsn.getString("number")));
                        }
                        if (number > 0) {
                            boolean b = rsn.executeUpdate(modBalanceSql, resourceid, outLeaves, newResidueAmount, resourceid, outLeaves);
                            bb.writeLog("KQBalanceOfLeaveJob number > 0 :resourceid = "+resourceid+" leaverulesid = " + outLeaves + " newResidueAmount = " + newResidueAmount + " status = " + b);
                        } else {
//                            "insert into kq_balanceOfLeave (leaverulesid,resourceid,belongyear,baseamount,extraamount," +
//                                    "usedamount,baseamount2,extraamount2,usedamount2,status,expirationDate,tiaoxiuamount) values (?,?,?,?,?,?," +
//                                    "?,?,?,?,?,?)";
                            String nextTwoYearDay = getNextTwoYearDay(nowDay);
                            boolean b = rsn.executeUpdate(addBalanceSql, outLeaves, resourceid, nowYear, newResidueAmount, 0.00,
                                    0.00, 0.00, 0.00, 0.00, 0, nextTwoYearDay, 0.0000);
                            bb.writeLog("KQBalanceOfLeaveJob number <= 0 :leaverulesid="+outLeaves+" resourceid="+resourceid+" " +
                                    "belongyear= "+nowYear+ " baseamount= "+newResidueAmount+ " expirationDate= "+nextTwoYearDay+" b = " +b);
                        }
                    }
                }
            }
            /*假期二开--外籍年假转结功能end*/

        } catch (Exception e) {
            kqLog.info(e);
        }
    }

    public static String getNextTwoYearDay(String currentDate){
        Calendar today = Calendar.getInstance();
        Date currDate = weaver.common.DateUtil.parseToDate(currentDate);
        today.setTime(currDate);
        today.add(Calendar.YEAR, 2);
        today.add(Calendar.DATE, -1);
        return  new SimpleDateFormat("yyyy-MM-dd").format(today.getTime());
    }
}
